<?php

namespace App\library\services;

use App\Models\Order;
use App\Models\UserConsume;

class UserConsumeService extends BaseServices
{
    /**
     * Author:Zhongyuan Lu
     * 用户消费记录
     * @param $uid
     * @param $order_no
     * @return array
     */
    public static function create($uid,$order_no)
    {
        $order = Order::where('order_no',$order_no)->first(['id','price','type','pay_type']);
        $order && $order = $order->toArray();
        if (empty($order)) {
            return self::fail('添加失败');
        }
        $payType = config('setting.pay_type')[$order['pay_type']];
        $type = config('setting.release_type')[$order['type']];

        $data = [
            'uid' => $uid,
            'order_id' => $order['id'],
            'name' => $payType.$type,    //消费记录名称    支付类型+发布类型
            'price' => $order['price'],     //支付金额
        ];

        $bool = UserConsume::create($data);
        if (empty($bool)) {
            return self::fail('添加创建失败');
        }
        return self::success('添加成功');
    }

    /**
     * Author:Zhongyuan Lu
     * 获取用户消费记录
     * @param $uid
     * @param $time
     * @return array
     */
    public static function getUserConsumeList($uid, $time)
    {
        $start_time = date('Y-m-01 00:00:00', strtotime($time));
        $end_time = date('Y-m-d 23:59:59', strtotime("{$start_time} +1 month -1 day"));
        $where = [
            ['uid', '=', $uid],
            ['created_at','between',[$start_time,$end_time]]
        ];
        //获取查询日期的当月所有消费记录
        $data = Order::where($where)->orderBy('id','desc')->get()->toArray();
        $total_price = 0;
        if (empty($data)) {
            $data['total_price'] = $total_price;
            return self::fail('暂无消费记录',$data);
        }

        foreach ($data as &$v) {
            $total_price = bcadd($total_price,$v['price']); //精度 加法
            $v['time'] = date('m-d h:i',strtotime($v['created_at']));
        }
        unset($v);
        $data['total_price'] = $total_price;
        return self::success('success',$data);
    }
}
